package com.sapuo.enroll.controller;


import com.sapuo.enroll.domain.CDKey;
import com.sapuo.enroll.domain.Enroll;
import com.sapuo.enroll.domain.EnrollDevice;
import com.sapuo.enroll.dto.RenewReq;
import com.sapuo.enroll.mapper.CDKeyMapper;
import com.sapuo.enroll.mapper.EnrollDeviceMapper;
import com.sapuo.enroll.mapper.EnrollMapper;
import com.sapuo.enroll.utils.CDKeyUtil;
import com.sapuo.enroll.utils.IpUtil;
import com.sapuo.enroll.utils.JwtUtil;
import com.sapuo.enroll.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@Slf4j
public class EnrollDeviceController {

    @Autowired
    EnrollDeviceMapper enrollDeviceMapper;

    @Autowired
    CDKeyMapper cdKeyMapper;

    private String miyao="66c5272f1f049cadea2d968d1226fadf";
    private String salt="zuogerenba";

    @RequestMapping(value = "device/renew", method = { RequestMethod.POST })
    @ResponseBody
    public R deviceRenew(HttpServletRequest request, HttpServletResponse response,
                       @RequestBody RenewReq renewReq) throws Exception {

        Map<String,Object> res = new HashMap<>();
        //验证激活码
        if(renewReq.getCdkey() == null){
            return R.error("1元激活，即可使用");
        }
        String deCDkey= "0";
        try {
            deCDkey = CDKeyUtil.deCDkey(renewReq.getCdkey(),"1");
            if("0".equals(deCDkey)){
                return  R.ok("激活状态异常，请联系管理员");
            }
        }catch (Exception e){
            return R.error("激活状态异常，请联系管理员");
        }

        EnrollDevice device = enrollDeviceMapper.getByCdkey(renewReq.getCdkey());
        if(device == null){
            return R.error("设备不存在，请联系管理员");
        }
        //验证签名
        String sign =md5(md5(renewReq.getCdkey()+miyao)+salt);
        if(!renewReq.getSign().equals(sign)){
            return R.error("激活状态异常，请联系管理员");

        }

        //激活码有效天数
        String code = deCDkey.substring(deCDkey.length() - 1);
        Integer day = CDKeyUtil.duetimeEnum(code);

        //激活天数
        Integer activeDay = daysBetween(device.getUpdateTime());

        //剩余天数
        int usable = day - activeDay;
        if("0".equals(code)){
            res.put("usable","SVIP~永久可用");
            res.put("days","-1");

        }else if (usable >0){
            res.put("usable","剩余"+usable+"天可用");
            res.put("days",String.valueOf(usable));

        }else{
            res.put("usable","0");
            res.put("days","0");

        }
        System.out.println(usable);
//        System.out.println(sign);
//
//        System.out.println(code);
//        System.out.println(day);

        return R.ok(res);


    }

    @RequestMapping(value = "device/add", method = { RequestMethod.POST })
    @ResponseBody
    public R deviceAdd(HttpServletRequest request, HttpServletResponse response,
                       @RequestBody EnrollDevice enrollDevice) throws Exception {
        Map<String,Object> res = new HashMap<>();

        //验证激活码
        if(enrollDevice.getCdkey() == null){
            return R.error("请输入正确激活码");
        }
        String deCDkey= "0";
        try {
            deCDkey = CDKeyUtil.deCDkey(enrollDevice.getCdkey(),"1");
            if("0".equals(deCDkey)){
                return  R.ok("请输入正确激活码");
            }
        }catch (Exception e){
            return R.error("请输入正确激活码");
        }

        CDKey cdKey = cdKeyMapper.getByCdkey(enrollDevice.getCdkey());
        if(cdKey == null){
            return R.error("激活码不存在，或已使用，请联系管理员");
        }

        String ip = IpUtil.getIpByIndex(request,1);
        //生成token
        String token = JwtUtil.token(enrollDevice.getFingerprint(),ip);

        System.out.println(token);

        EnrollDevice device = new EnrollDevice();
        device.setFingerprint(enrollDevice.getFingerprint());
        device.setImei(enrollDevice.getImei());
        device.setMac(enrollDevice.getMac());
        device.setIp(ip);
        device.setCdkey(cdKey.getCdkey());
        device.setCdkeyId(cdKey.getId());
        device.setCreateTime(new Date());
        device.setUpdateTime(new Date());
        device.setToken(token);
        Integer insert  = enrollDeviceMapper.insert(device);

        if(insert>0){

            CDKey cd = new CDKey();
            cd.setId(cdKey.getId());
            cd.setIsUsed(1);
            cd.setUseTime(new Date());
            cd.setUpdateTime(new Date());
            cdKeyMapper.update(cd);

            String sign =md5(md5(cdKey.getCdkey()+miyao)+salt);
            res.put("token",token);
            res.put("sign",sign);

            //激活码有效天数
            String code = deCDkey.substring(deCDkey.length() - 1);
            int day = CDKeyUtil.duetimeEnum(code);
            //可用天数
            if("0".equals(code)){
                res.put("usable","SVIP~永久可用");
                res.put("days","-1");

            }else{
                res.put("usable","剩余"+day+"天可用");
                res.put("days",String.valueOf(day));

            }

            return R.ok(res);
        }

        return R.error("非常抱歉，激活失败了，请联系管理员");
    }

    public String md5(String str){
        return DigestUtils.md5DigestAsHex(str.getBytes());
    }


    public static int daysBetween(Date activeTime) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String now =format.format(new Date());
        Date nowDate = format.parse(now);

        int a = (int) ((nowDate.getTime() - activeTime.getTime()) / (1000*3600*24));
        return a;
    }


//    public static void main(String[] args) {
//        String md5Str = DigestUtils.md5DigestAsHex("aI5y3kl6+jrnk15".getBytes());
//        System.out.println(md5Str);
//    }

}
